<template>
	<!-- H5 环境使用专门的 HTML5 摄像头组件 -->
	<!-- #ifdef H5 -->
	<html5-camera
		:width="400"
		:height="300"
		@success="handleSuccess"
		@cancel="handleCancel"
		@error="handleError"
	/>
	<!-- #endif -->

	<!-- App 和小程序环境使用原生摄像头组件 -->
	<!-- #ifndef H5 -->
	<view class="face-camera-container">
		<!-- 摄像头预览区域 -->
		<view class="camera-section">
			<view class="camera-wrapper">
				<!-- 摄像头组件 -->
				<camera
					v-if="showCamera"
					class="camera-preview"
					device-position="front"
					flash="off"
					@error="onCameraError"
					@initdone="onCameraReady"
				>
					<!-- 人脸识别框 -->
					<view class="face-guide">
						<view class="face-frame">
							<view class="corner corner-tl"></view>
							<view class="corner corner-tr"></view>
							<view class="corner corner-bl"></view>
							<view class="corner corner-br"></view>
						</view>
						<text class="guide-text">{{ guideText }}</text>
					</view>
				</camera>
				
				<!-- 拍照预览 -->
				<view v-if="capturedImage" class="captured-preview">
					<image :src="capturedImage" class="captured-image" mode="aspectFit"></image>
					<view class="preview-overlay">
						<text class="preview-text">照片预览</text>
					</view>
				</view>
			</view>
			
			<!-- 操作按钮区域 -->
			<view class="controls-section">
				<view class="control-buttons">
					<!-- 重新拍照按钮 -->
					<button 
						v-if="capturedImage" 
						class="btn btn-secondary retake-btn"
						@click="retakePhoto"
					>
						<text class="btn-icon">🔄</text>
						<text>重新拍照</text>
					</button>
					
					<!-- 拍照按钮 -->
					<button 
						v-if="!capturedImage && cameraReady" 
						class="btn btn-primary capture-btn"
						:class="{ 'btn-loading': isCapturing }"
						:disabled="isCapturing"
						@click="capturePhoto"
					>
						<text v-if="isCapturing">拍照中...</text>
						<text v-else>
							<text class="btn-icon">📷</text>
							<text>拍照</text>
						</text>
					</button>
					
					<!-- 确认按钮 -->
					<button 
						v-if="capturedImage" 
						class="btn btn-primary confirm-btn"
						:class="{ 'btn-loading': isProcessing }"
						:disabled="isProcessing"
						@click="confirmPhoto"
					>
						<text v-if="isProcessing">处理中...</text>
						<text v-else>
							<text class="btn-icon">✓</text>
							<text>确认使用</text>
						</text>
					</button>
				</view>
				
				<!-- 取消按钮 -->
				<button class="btn btn-text cancel-btn" @click="cancelCapture">
					<text>取消</text>
				</button>
			</view>
		</view>
		
		<!-- 提示信息 -->
		<view class="tips-section">
			<view class="tips-content">
				<text class="tips-title">拍照提示</text>
				<view class="tips-list">
					<text class="tip-item">• 请保持面部在框内</text>
					<text class="tip-item">• 确保光线充足</text>
					<text class="tip-item">• 保持表情自然</text>
					<text class="tip-item">• 避免佩戴口罩或墨镜</text>
				</view>
			</view>
		</view>
	</view>
	<!-- #endif -->
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
// #ifdef H5
import Html5Camera from './html5-camera.vue'
// #endif

// Props
const props = defineProps({
	mode: {
		type: String,
		default: 'register', // register | login
		validator: (value) => ['register', 'login'].includes(value)
	}
})

// Emits
const emit = defineEmits(['success', 'cancel', 'error'])

// 响应式数据
const showCamera = ref(false)
const cameraReady = ref(false)
const capturedImage = ref('')
const isCapturing = ref(false)
const isProcessing = ref(false)
const guideText = ref('请将面部对准框内')

// 生命周期
onMounted(() => {
	initCamera()
})

onUnmounted(() => {
	cleanup()
})

// 方法
const initCamera = async () => {
	try {
		// 检查平台并请求摄像头权限
		// #ifdef APP-PLUS || MP
		if (uni.authorize) {
			const authResult = await new Promise((resolve, reject) => {
				uni.authorize({
					scope: 'scope.camera',
					success: (res) => {
						resolve(res)
					},
					fail: (err) => {
						// 权限被拒绝，尝试打开设置页面
						uni.showModal({
							title: '需要摄像头权限',
							content: '请在设置中开启摄像头权限',
							confirmText: '去设置',
							cancelText: '取消',
							success: (modalRes) => {
								if (modalRes.confirm) {
									uni.openSetting({
										success: (settingRes) => {
											if (settingRes.authSetting['scope.camera']) {
												resolve(settingRes)
											} else {
												reject(new Error('用户未开启摄像头权限'))
											}
										},
										fail: () => {
											reject(new Error('无法打开设置页面'))
										}
									})
								} else {
									reject(new Error('用户拒绝开启摄像头权限'))
								}
							}
						})
					}
				})
			})
		}
		// #endif

		// #ifdef H5
		// H5 环境下，摄像头权限由浏览器管理，直接显示摄像头
		console.log('H5 环境，直接启用摄像头')
		// #endif

		showCamera.value = true
		guideText.value = '请将面部对准框内'

	} catch (error) {
		console.error('初始化摄像头失败:', error)
		handleCameraError('无法访问摄像头，请检查权限设置')
	}
}

const onCameraReady = () => {
	cameraReady.value = true
	guideText.value = '摄像头已就绪，点击拍照'
}

const onCameraError = (error) => {
	console.error('摄像头错误:', error)
	handleCameraError('摄像头启动失败')
}

const handleCameraError = (message) => {
	uni.showModal({
		title: '摄像头错误',
		content: message,
		showCancel: false,
		confirmText: '确定',
		success: () => {
			emit('error', message)
		}
	})
}

const capturePhoto = async () => {
	if (!cameraReady.value || isCapturing.value) return

	isCapturing.value = true
	guideText.value = '正在拍照...'

	try {
		// #ifdef APP-PLUS || MP
		// App 和小程序环境使用 uni.createCameraContext
		if (uni.createCameraContext) {
			const cameraContext = uni.createCameraContext()

			cameraContext.takePhoto({
				quality: 'high',
				success: (res) => {
					capturedImage.value = res.tempImagePath
					showCamera.value = false
					guideText.value = '拍照完成'

					uni.showToast({
						title: '拍照成功',
						icon: 'success',
						duration: 1000
					})
				},
				fail: (error) => {
					console.error('拍照失败:', error)
					uni.showToast({
						title: '拍照失败，请重试',
						icon: 'none',
						duration: 2000
					})
					guideText.value = '拍照失败，请重试'
				}
			})
		}
		// #endif

		// #ifdef H5
		// H5 环境下使用 Canvas 截取摄像头画面
		await captureFromH5Camera()
		// #endif

	} catch (error) {
		console.error('拍照异常:', error)
		uni.showToast({
			title: '拍照异常',
			icon: 'none',
			duration: 2000
		})
		guideText.value = '拍照异常，请重试'
	} finally {
		isCapturing.value = false
	}
}

// H5 环境下的拍照方法
const captureFromH5Camera = async () => {
	try {
		// 模拟拍照成功（实际项目中需要实现 Canvas 截图）
		// 这里先用一个模拟的图片路径
		const mockImagePath = ''

		capturedImage.value = mockImagePath
		showCamera.value = false
		guideText.value = '拍照完成'

		uni.showToast({
			title: '拍照成功（模拟）',
			icon: 'success',
			duration: 1000
		})

		console.log('H5 环境模拟拍照成功')
	} catch (error) {
		throw error
	}
}

const retakePhoto = () => {
	capturedImage.value = ''
	showCamera.value = true
	guideText.value = '请将面部对准框内'
}

const confirmPhoto = async () => {
	if (!capturedImage.value || isProcessing.value) return
	
	isProcessing.value = true
	
	try {
		// 根据模式执行不同的人脸识别逻辑
		if (props.mode === 'login') {
			// 登录模式 - 人脸识别验证
			guideText.value = '正在进行人脸识别...'
			
			// 模拟人脸识别处理时间
			await new Promise(resolve => setTimeout(resolve, 2000))
			
			// 模拟人脸识别结果 (实际项目中应该调用后端API)
			const loginSuccess = Math.random() > 0.2 // 80% 成功率
			
			if (loginSuccess) {
				// 登录成功
				emit('success', {
					imagePath: capturedImage.value,
					mode: props.mode,
					result: 'success'
				})
			} else {
				// 登录失败
				throw new Error('人脸识别失败，请重试')
			}
		} else {
			// 注册模式 - 人脸录入
			guideText.value = '正在处理人脸信息...'
			
			// 模拟处理时间
			await new Promise(resolve => setTimeout(resolve, 1500))
			
			// 返回拍照结果
			emit('success', {
				imagePath: capturedImage.value,
				mode: props.mode
			})
		}
		
	} catch (error) {
		console.error('处理照片失败:', error)
		uni.showToast({
			title: error.message || '处理失败，请重试',
			icon: 'none',
			duration: 2000
		})
	} finally {
		isProcessing.value = false
	}
}

const cancelCapture = () => {
	emit('cancel')
}

const cleanup = () => {
	showCamera.value = false
	cameraReady.value = false
	capturedImage.value = ''
}

// H5 环境下的事件处理方法
// #ifdef H5
const handleSuccess = (result) => {
	emit('success', result)
}

const handleCancel = () => {
	emit('cancel')
}

const handleError = (error) => {
	emit('error', error)
}
// #endif
</script>

<style lang="scss" scoped>
.face-camera-container {
	height: 100vh;
	background: #000000;
	display: flex;
	flex-direction: column;
}

.camera-section {
	flex: 1;
	display: flex;
	flex-direction: column;
	position: relative;
}

.camera-wrapper {
	flex: 1;
	position: relative;
	overflow: hidden;
}

.camera-preview {
	width: 100%;
	height: 100%;
}

.face-guide {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	z-index: 10;
}

.face-frame {
	width: 240px;
	height: 300px;
	position: relative;
	border: 2px solid rgba(255, 255, 255, 0.3);
	border-radius: 120px;
}

.corner {
	position: absolute;
	width: 30px;
	height: 30px;
	border: 3px solid #00ff00;
	
	&.corner-tl {
		top: -3px;
		left: -3px;
		border-right: none;
		border-bottom: none;
		border-radius: 15px 0 0 0;
	}
	
	&.corner-tr {
		top: -3px;
		right: -3px;
		border-left: none;
		border-bottom: none;
		border-radius: 0 15px 0 0;
	}
	
	&.corner-bl {
		bottom: -3px;
		left: -3px;
		border-right: none;
		border-top: none;
		border-radius: 0 0 0 15px;
	}
	
	&.corner-br {
		bottom: -3px;
		right: -3px;
		border-left: none;
		border-top: none;
		border-radius: 0 0 15px 0;
	}
}

.guide-text {
	display: block;
	text-align: center;
	color: #ffffff;
	font-size: 16px;
	margin-top: 20px;
	text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

.captured-preview {
	width: 100%;
	height: 100%;
	position: relative;
	background: #000000;
	display: flex;
	align-items: center;
	justify-content: center;
}

.captured-image {
	max-width: 100%;
	max-height: 100%;
}

.preview-overlay {
	position: absolute;
	top: 20px;
	left: 50%;
	transform: translateX(-50%);
	background: rgba(0, 0, 0, 0.7);
	padding: 8px 16px;
	border-radius: 20px;
}

.preview-text {
	color: #ffffff;
	font-size: 14px;
}

.controls-section {
	padding: 20px;
	background: rgba(0, 0, 0, 0.8);
}

.control-buttons {
	display: flex;
	justify-content: center;
	gap: 16px;
	margin-bottom: 16px;
}

.btn {
	padding: 12px 24px;
	border-radius: 25px;
	font-size: 16px;
	font-weight: 600;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 8px;
	transition: all 0.3s ease;
	
	&.btn-primary {
		background: linear-gradient(135deg, #007AFF 0%, #0051D5 100%);
		color: #ffffff;
		box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
		
		&:hover {
			transform: translateY(-2px);
			box-shadow: 0 6px 16px rgba(0, 122, 255, 0.4);
		}
	}
	
	&.btn-secondary {
		background: rgba(255, 255, 255, 0.1);
		color: #ffffff;
		border: 1px solid rgba(255, 255, 255, 0.3);
		
		&:hover {
			background: rgba(255, 255, 255, 0.2);
		}
	}
	
	&.btn-text {
		background: transparent;
		color: rgba(255, 255, 255, 0.7);
		
		&:hover {
			color: #ffffff;
		}
	}
	
	&.btn-loading {
		opacity: 0.7;
		pointer-events: none;
	}
	
	&:disabled {
		opacity: 0.5;
		pointer-events: none;
	}
}

.btn-icon {
	font-size: 18px;
}

.capture-btn {
	min-width: 120px;
}

.confirm-btn {
	min-width: 120px;
}

.cancel-btn {
	width: 100%;
	text-align: center;
}

.tips-section {
	background: rgba(0, 0, 0, 0.9);
	padding: 16px 20px;
}

.tips-content {
	max-width: 300px;
	margin: 0 auto;
}

.tips-title {
	display: block;
	color: #ffffff;
	font-size: 16px;
	font-weight: 600;
	margin-bottom: 12px;
	text-align: center;
}

.tips-list {
	display: flex;
	flex-direction: column;
	gap: 6px;
}

.tip-item {
	color: rgba(255, 255, 255, 0.8);
	font-size: 14px;
	line-height: 1.4;
}
</style>